package com.huahua.config;

import com.huahua.enums.ExceptionEnum;
import com.huahua.exception.BusinessException;
import com.huahua.resp.R;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * RestControllerAdvice，统一异常处理
 *
 * @author huahua
 */
@Slf4j
@RestControllerAdvice
public class ExceptionHandlerConfig {

    /**
     * 业务异常处理
     *
     * @param e 业务异常
     * @return
     */
    @ExceptionHandler(value = BusinessException.class)
    @ResponseBody
    public R exceptionHandler(BusinessException e) {
        return R.fail(Integer.valueOf(e.getCode()), e.getErrorMsg());
    }

    /**
     * 未知异常处理
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public R exceptionHandler(Exception e) {
        return R.fail(Integer.valueOf(ExceptionEnum.UNKNOWN.getCode()),
                ExceptionEnum.UNKNOWN.getMsg());
    }

    /**
     * 空指针异常
     */
    @ExceptionHandler(value = NullPointerException.class)
    @ResponseBody
    public R exceptionHandler(NullPointerException e) {
        return R.fail(Integer.valueOf(ExceptionEnum.INTERNAL_SERVER_ERROR.getCode()),
                ExceptionEnum.INTERNAL_SERVER_ERROR.getMsg());
    }
}